﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Finance;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.Finance;
using AMM.UserControls;

namespace AMM.Forms.Finance {
    public partial class FrmStatement : FrmStatementBase {

        private int _pageIndex;
        private StatementSearchModel _searchModel;
        private StatementProcessor _statementProcessor;
        private List<StatementViewModel> _statementList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1703"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new StatementSearchControl(); }
        }

        protected override void Add() {
            if (this._statementProcessor.CheckStatementPrerequisite(DateTime.Now)) {
                this.ShowError("本月有暂收单未入库，不能生成月结单！");
                return;
            }
            this.CreateNewThread(() => {
                string autoCode = CommonHelper.GenerateAutoCode("SP");
                int maxNumber = this._statementProcessor.GetTheMaxFlowNumber(autoCode);
                string code = CommonHelper.GendrateSpecificCode(autoCode, maxNumber);
                this._statementProcessor.GenerateStatement(code, LoginUserName, DateTime.Now);
            }, () => {
                this.ResetForms();
                base.Add();
            });
        }

        protected override void Audit() {
            List<StatementViewModel> selectedList = this.dgvStatementList.GetSelectedRows<StatementViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                string resultMsg = string.Empty;
                Statement statement = this._statementProcessor.FetchStatementById(selectedList[0].Key);
                if (statement.Status == (int)AuditStatus.Audited) {
                    if (this.ShowQuestion("订单已经通过审核，确定将取消审核状态！") == DialogResult.No) { return; }
                    statement.Status = (int)AuditStatus.Waiting;
                    resultMsg = "取消审核成功";
                }
                else {
                    statement.Status = (int)AuditStatus.Audited;
                    resultMsg = "审核成功";
                }
                statement.AuditedBy = LoginUserName;
                this._statementProcessor.Audit(statement);
                this.MDIParent.SetStatusInformation(resultMsg);
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Audit();
            });
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new StatementSearchModel();
                }
                else {
                    this._searchModel = (StatementSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindStatementList();
            });
        }

        #endregion

        public FrmStatement() {
            this.InitializeComponent();

            this.dgvStatementList.DataGridViewModelType = typeof(StatementViewModel);
            this.dgvStatementDetailList.DataGridViewModelType = typeof(StatementDetailsViewModel);
        }

        #region Private methods

        private void ResetForms() {
            this.BindStatementList();
            this.BindStatementDetailsList(0);
        }

        private void BindStatementList() {
            this.CreateNewThread(() => {
                this._statementList = this._statementProcessor.FetchStatementViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvStatementList.DataSource = new SortableBindingList<StatementViewModel>(this._statementList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindStatementDetailsList(int suspenseId) {
            List<StatementDetailsViewModel> detailsList = new List<StatementDetailsViewModel>();
            this.CreateNewThread(() => {
                if (suspenseId != 0) {
                    detailsList = this._statementProcessor.FetchStatementDetailsViewModelList(suspenseId);
                }
            }, () => {
                this.dgvStatementDetailList.DataSource = new SortableBindingList<StatementDetailsViewModel>(detailsList);
            });
        }

        #endregion

        private void FrmStatement_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._statementProcessor = new StatementProcessor(this.pceList.PageSize);
                this._searchModel = new StatementSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindStatementList();
        }

        private void dgvStatementList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvStatementList.CurrentRow != null) {
                int suspenseId = (int)this.dgvStatementList.CurrentRow.Cells["Key"].Value;
                this.BindStatementDetailsList(suspenseId);
            }
        }
    }
}
